package juc.scenarios.startup.service.impl;

import juc.scenarios.startup.model.ServiceStatus;
import juc.scenarios.startup.service.HealthCheckService;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 消息队列健康检查服务
 */
public class MessageQueueHealthCheckService implements HealthCheckService {

    private static final String SERVICE_NAME = "消息队列服务";
    private static final Random RANDOM = new Random();

    @Override
    public ServiceStatus checkHealth() {
        LocalDateTime startTime = LocalDateTime.now();

        try {
            // 模拟消息队列连接检查
            ServiceStatus.ServiceState state = performMessageQueueCheck();

            LocalDateTime endTime = LocalDateTime.now();
            long duration = java.time.Duration.between(startTime, endTime).toMillis();


            return ServiceStatus.builder()
                    .serviceName(SERVICE_NAME)
                    .state(state)
                    .message(state == ServiceStatus.ServiceState.HEALTHY ? "消息队列服务正常" : "消息队列服务异常")
                    .startTime(startTime)
                    .endTime(endTime)
                    .duration(duration)
                    .build();

        } catch (Exception e) {
            LocalDateTime endTime = LocalDateTime.now();
            long duration = java.time.Duration.between(startTime, endTime).toMillis();

            return ServiceStatus.builder()
                    .serviceName(SERVICE_NAME)
                    .state(ServiceStatus.ServiceState.UNHEALTHY)
                    .message("消息队列检查异常: " + e.getMessage())
                    .startTime(startTime)
                    .endTime(endTime)
                    .duration(duration)
                    .build();
        }
    }

    @Override
    public String getServiceName() {
        return SERVICE_NAME;
    }

    @Override
    public long getTimeout() {
        return 4000L; // 消息队列检查超时时间4秒
    }

    /**
     * 模拟消息队列检查
     */
    private ServiceStatus.ServiceState performMessageQueueCheck() throws InterruptedException {
        // 模拟检查耗时（1-3秒）
        long checkTime = 1000 + RANDOM.nextInt(2000);
        TimeUnit.MILLISECONDS.sleep(checkTime);

        // 95%概率正常，5%概率异常
        return RANDOM.nextDouble() < 0.95 ?
                ServiceStatus.ServiceState.HEALTHY :
                ServiceStatus.ServiceState.UNHEALTHY;
    }
}